package com.ykzhujiang.lovespirit.labor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.Stack;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ykzhujiang.lovespirit.util.Utility;

public class SJTULabor extends Labor {
	public static class ValuableLabor extends Labor {
		public int Fetch(int num) {
			int count = 0;
			urls.clear();
			urls.push(url_text);
			while (count < num && !urls.empty()) {
				String url = urls.pop();
				String text = Utility.GetURLText(url, connect_times);
				if (text == null) {
					return -1;
				}
				Pattern p = Pattern.compile(directory_pattern);
				Matcher m = p.matcher(text);
				while (m.find()) {
					String raw = url_root + m.group(2);
					if (!urls.contains(raw)) {
						urls.push(raw);
					}
				}
				p = Pattern.compile(file_pattern);
				m = p.matcher(text);
				while (m.find()) {
					String raw = url_root + m.group(2);
					if (!files.contains(raw)) {
						if (count++ < num) {
							files.add(raw);
						} else {
							break;
						}
					}
				}
			}
			return 0;
		}

		private String url_root = "http://bbs.sjtu.edu.cn/";

		private String board = "love";

		private String group = "8";

		private String directory_pattern = "(<td>\\[目录\\] <td><a href=)(.*?)>";

		private String file_pattern = "(<td>\\[文件\\] <td><a href=)(.*?)>";

		private String url_text = "http://bbs.sjtu.edu.cn/bbs0an,path,/groups/GROUP_"
				+ group + "/" + board + ".html";

		private Stack<String> urls = new Stack<String>();

		public synchronized String getBoard() {
			return board;
		}

		public synchronized void setBoard(String board) {
			this.board = board;
			url_text = "http://bbs.sjtu.edu.cn/bbs0an,path,/groups/GROUP_"
					+ group + "/" + board + ".html";
		}

		public synchronized String getGroup() {
			return group;
		}

		public synchronized void setGroup(String group) {
			this.group = group;
			url_text = "http://bbs.sjtu.edu.cn/bbs0an,path,/groups/GROUP_"
					+ group + "/" + board + ".html";
		}
	}

	public int Login(String userid, String pw) {
		utmpuserid = userid;
		utmpuserpw = pw;
		while (System.currentTimeMillis() - last_login_time < 5000) {
			try {
				logger.info("Sleep for next login");
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				logger.warning(e.toString());
				logger.warning(e.getMessage());
			}
		}
		last_login_time = System.currentTimeMillis();
		String ltext = Utility.GetURLText(url_login + "id=" + utmpuserid
				+ "&pw=" + utmpuserpw, connect_times);
		// logger.info(ltext);
		if (ltext == null)
			return -1;
		Pattern p = Pattern.compile(cookie_pattern);
		Matcher m = p.matcher(ltext);
		if (m.find()) {
			utmpnum = m.group(1);
			utmpkey = m.group(2);
			utmpuserid = m.group(3);
		} else {
			logger.info("Login Fail");
			return -1;
		}
		logger.info("Login Success");
		logger.info("utmpnum: " + utmpnum);
		logger.info("utmpkey: " + utmpkey);
		logger.info("utmpuserid: " + utmpuserid);
		return 0;
	}

	public int Post(String title, String text) {

		while (System.currentTimeMillis() - last_post_time < 5000) {
			try {
				logger.info("Sleep for next post");
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				logger.warning(e.toString());
				logger.warning(e.getMessage());
			}
		}
		last_post_time = System.currentTimeMillis();
		try {

			HttpURLConnection connection = (HttpURLConnection) Utility
					.GetURLConnection(url_post, connect_times);
			if (connection == null)
				return -1;
			connection.setRequestMethod("POST");
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestProperty("Cookie", "utmpnum=" + utmpnum
					+ "; utmpkey=" + utmpkey + "; utmpuserid=" + utmpuserid);

			PrintWriter out = new PrintWriter(connection.getOutputStream());
			String pboard = "board=" + URLEncoder.encode(this.board, "GBK");
			String ptitle = "title=" + URLEncoder.encode(title, "GBK");
			String ptext = "text=" + URLEncoder.encode(text, "GBK");

			out.println(pboard + "&" + ptitle + "&" + ptext);
			out.close();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			StringBuffer sb = new StringBuffer();
			String line;
			while ((line = in.readLine()) != null) {
				sb.append(line);
				sb.append("\r\n");
			}
			in.close();
			Pattern p = Pattern.compile(post_fail_pattern);
			Matcher m = p.matcher(sb.toString());
			if (m.find()) {
				if (Login(utmpuserid, utmpuserpw) != -1) {
					return Post(title, text);
				} else {
					logger.info("Post Fail");
					return -1;
				}
			}
			logger.info("Post Success");

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			logger.warning(e.toString());
			logger.warning(e.getMessage());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.warning(e.toString());
			logger.warning(e.getMessage());
		}
		return 0;
	}

	public int Fetch(int page_num) {
		int count = 0;
		String url = url_text;
		while (count++ < page_num && url != null) {
			String text = Utility.GetURLText(url, connect_times);
			if (text == null) {
				return -1;
			}
			Pattern p = Pattern.compile(thread_pattern);
			Matcher m = p.matcher(text);
			while (m.find()) {
				String raw = thread_pattern2 + m.group(1);
				if (!files.contains(raw)) {
					files.add(raw);
				}
			}
			p = Pattern.compile(page_pattern);
			m = p.matcher(text);
			if (m.find()) {
				url = url_root + m.group(0);
			} else {
				url = null;
			}
		}
		return 0;
	}

	public void SetBoard(String board) {
		this.board = board;
		thread_pattern = "bbstcon,board," + board + ",reid,(.*?)\\.html(?=>)";
		thread_pattern2 = "http://bbs.sjtu.edu.cn/bbstcon?board=" + board
				+ "&showall=true&reid=";
		page_pattern = "bbstdoc,board," + board + ",page,.*?(?=>)";
		url_text = "http://bbs.sjtu.edu.cn/bbstdoc,board," + board + ".html";
		url_root = "http://bbs.sjtu.edu.cn/";
	}

	public String GetBorad() {
		return board;
	}

	private long last_post_time = 0;

	private long last_login_time = 0;

	private String board = "LoveBridge";

	private String thread_pattern = "bbstcon,board," + board
			+ ",reid,(.*?)\\.html(?=>)";

	private String thread_pattern2 = "http://bbs.sjtu.edu.cn/bbstcon?board="
			+ board + "&showall=true&reid=";
	private String page_pattern = "bbstdoc,board," + board + ",page,.*?(?=>)";

	private String url_text = "http://bbs.sjtu.edu.cn/bbstdoc,board," + board
			+ ".html";

	private String url_root = "http://bbs.sjtu.edu.cn/";

	private String url_login = "http://bbs.sjtu.edu.cn/bbslogin?";

	private String url_post = "http://bbs.sjtu.edu.cn/bbssnd";

	private static String utmpnum = "";

	private static String utmpkey = "";

	private static String utmpuserid = "";

	private static String utmpuserpw = "";

	private String cookie_pattern = "(?s).*?utmpnum=(\\d{1,4}?)(?=')(?s).*?utmpkey=(\\d{1,10}?)(?=')(?s).*?utmpuserid=(\\w{1,12}?)(?=')(?s).*?";

	private String post_fail_pattern = "匆匆过客不能发表文章";

	// private static Logger logger = Logger.getLogger(SJTULabor.class);
	private final Logger logger = Logger.getLogger(SJTULabor.class.getName());
}
